﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Algobox.JuicyLib.SQL.LiquidView;
using System.Data.Linq;
using System.Net;

namespace Algobox.JuicyLib.Apps.FTEN
{
    public class FTENFileDrop : IDisposable
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileDate">File date to generate the files for</param>
        /// <param name="ftplocation">URI inclusing the directory of where to save the files</param>
        /// <param name="user">FTP username</param>
        /// <param name="pass">FTP password</param>
        public FTENFileDrop()
        {
            m_Linq = new Algobox.JuicyLib.SQL.LiquidView.LiquidViewLinqDataContext();
        }

        public FTENFileDrop(string connection)
        {
            m_Linq = new Algobox.JuicyLib.SQL.LiquidView.LiquidViewLinqDataContext(connection);
        }

        const string PROCESSNAME = "FTPFileDrop";

        Algobox.JuicyLib.SQL.LiquidView.LiquidViewLinqDataContext m_Linq;
        
        public void Dispose()
        {
            m_Linq.Dispose();
        }

        public void RunPositionFileDrop(DateTime fileDate, string destination, string username, string password)
        {
            string positions = String.Empty;
            try
            {
                positions = GetPositions(fileDate);
            }
            catch (Exception e)
            {
                Console.WriteLine("Position file failed to be generated\r\n" + e);
                m_Linq.ExceptionHandlerThrow(PROCESSNAME, "Failed to load FTEN Positions from database", null);
            }

            string filename = String.Empty; 

            WebClient client = new WebClient();
            client.Credentials = new NetworkCredential(username, password);

            try
            {
                if (positions != String.Empty)
                {
                    filename = destination.ToString() + "positions_" + fileDate.ToString("yyyyMMdd") + ".txt";
                    Console.WriteLine("Writing Positions to " + filename);
                    client.UploadData(filename, System.Text.Encoding.UTF8.GetBytes(positions));
                    m_Linq.LogGeneral(PROCESSNAME, "RunPositionFileDrop", "Success", "Wrote positions to " + filename, null, null, null, null, null, null);  
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("FX file failed to get uploaded\r\n" + e);
                m_Linq.ExceptionHandlerThrow(PROCESSNAME, "Position file failed to get uploaded - " + e, null);
            }  
            

        }



        private string GetPositions(DateTime snapshotDate)
        {
            StringBuilder output = new StringBuilder();
            foreach (GetDataViewSnapshotDailyStockResult data in m_Linq.GetDataViewSnapshotDailyStock(snapshotDate))
            {
                string accountId = data.AccountId.Substring(data.AccountId.LastIndexOf('_') + 1);
                output.AppendFormat("{0},{1},{2},{3},{4},{5}\n", accountId, data.Symbol, data.CurrentPosition > 0 ? "L" : "S", data.CurrentPosition, data.CurrentSettlement, data.Currency);
            }
            return output.ToString();
        }


        public void RunFXFileDrop(DateTime fileDate, string destination, string username, string password)
        {
            string fx = String.Empty;
            try
            {
                fx = GetFX(fileDate);
            }
            catch (Exception e)
            {
                Console.WriteLine("FX file failed to be generated\r\n" + e);
                m_Linq.ExceptionHandlerThrow(PROCESSNAME, "Failed to load FTEN FX rates from database", null);
            }

            string filename = String.Empty;

            WebClient client = new WebClient();
            client.Credentials = new NetworkCredential(username, password);

            try
            {
                if (fx != String.Empty)
                {
                    filename = destination.ToString() + "gbpFxRates_" + fileDate.ToString("yyyyMMdd") + ".txt";
                    Console.WriteLine("Writing FX to " + filename);
                    client.UploadData(filename, System.Text.Encoding.UTF8.GetBytes(fx));
                    m_Linq.LogGeneral(PROCESSNAME, "RunFXFileDrop", "Success", "Wrote positions to " + filename, null, null, null, null, null, null);  
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("FX file failed to get uploaded\r\n" + e);
                m_Linq.ExceptionHandlerThrow(PROCESSNAME, "FX file failed to get uploaded - " + e, null);
            }


        }



        private string GetFX(DateTime snapshotDate)
        {
            StringBuilder output = new StringBuilder();
            output.Append("GBP:100\n");

            decimal? rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "EUR", ref rate);

            if (rate.HasValue)
                output.AppendFormat("EUR:{0}\n", rate.Value * 100);

            rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "USD", ref rate);

            if (rate.HasValue)
                output.AppendFormat("USD:{0}\n", rate.Value * 100);

            rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "CHF", ref rate);

            if (rate.HasValue)
                output.AppendFormat("CHF:{0}\n", rate.Value * 100);

            rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "NOK", ref rate);

            if (rate.HasValue)
                output.AppendFormat("NOK:{0}\n", rate.Value * 100);

            rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "DKK", ref rate);

            if (rate.HasValue)
                output.AppendFormat("DKK:{0}\n", rate.Value * 100);

            rate = null;
            m_Linq.GetFXRate(snapshotDate, "GBP", "SEK", ref rate);

            if (rate.HasValue)
                output.AppendFormat("SEK:{0}\n", rate.Value * 100);

            return output.ToString();
        }


    }
}
